<?php

namespace Xin\EasyQueue\Webman;

use Webman\RedisQueue\Redis;
use Webman\RedisQueue\RedisConnection;
use Xin\EasyQueue\Contracts\QueueInfo;
use Xin\Support\Arr;

class RedisQueueInfo implements QueueInfo
{
    /**
     * @var string
     */
    protected $queue;

    /**
     * @var string
     */
    protected $connection;

    /**
     * @var RedisConnection
     */
    protected $redis;

    /**
     * @var string
     */
    protected $waitingNameSuffix = '{redis-queue}-waiting';

    /**
     * @var string
     */
    protected $delayedNameSuffix = '{redis-queue}-delayed';


    /**
     * @param $queue
     * @param $connection
     */
    public function __construct($queue, $connection)
    {
        $this->queue = $queue;
        $this->connection = $connection;
        $this->redis = Redis::connection($this->connection);
    }

    /**
     * @inerhitDoc
     */
    public function waiting(int $start = 0, int $end = -1): array
    {
        return $this->redis->lRange($this->waitingNameSuffix . $this->queue, $start, $end);
    }

    /**
     * @inerhitDoc
     */
    public function waitingName(): string
    {
        return Arr::get($this->getRedisConfig(), 'prefix', '') . $this->waitingNameSuffix . $this->queue;
    }

    /**
     * @inerhitDoc
     */
    public function waitingCount(): int
    {
        return $this->redis->lLen($this->waitingNameSuffix . $this->queue);
    }

    /**
     * @inerhitDoc
     */
    public function delayed(int $start = 0, int $end = -1): array
    {
        $data = $this->redis->zRange($this->delayedNameSuffix, $start, $end);
        return array_filter($data, function ($item) {
            return stripos($item, "\"queue\":\"{$this->queue}\"") !== false;
        });
    }

    /**
     * @inerhitDoc
     */
    public function delayedName(): string
    {
        return Arr::get($this->getRedisConfig(), 'prefix', '') . $this->delayedNameSuffix;
    }

    /**
     * @inerhitDoc
     */
    public function delayedCount(): int
    {
        return count($this->delayed());
//        return $this->redis->zCard($this->delayedNameSuffix);
    }

    /**
     * @return array
     */
    protected function getRedisConfig()
    {
        $redisClass = new \ReflectionClass($this->redis);
        $property = $redisClass->getProperty('config');
        $property->setAccessible(true);
        return $property->getValue($this->redis);
    }
}
